package com.tyut.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tyut.entity.User;


public class JwtUtil {
    // 密钥, 随便写，只要不被别人知道即可
    private static final String KEY = "YAMADA";
    // 生成token
    public static String create(User user) {
        return JWT.create().withClaim("id", user.getId())
                .withClaim("username", user.getUsername())
                .withClaim("name", user.getName())
                .withClaim("email", user.getEmail())
                .withClaim("phone", user.getPhone())
                .withClaim("role", user.getRole())
                .sign((Algorithm.HMAC256(KEY)));
    }
    // 解析token
    public static User parse(String jwtStr) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(KEY))
                .build().verify(jwtStr);

        User user = new User();
        user.setId(verify.getClaim("id").asInt());
        user.setUsername(verify.getClaim("username").asString());
        user.setName(verify.getClaim("name").asString());
        user.setEmail(verify.getClaim("email").asString());
        user.setPhone(verify.getClaim("phone").asString());
        user.setRole(verify.getClaim("role").asInt());
        return user;
    }
}
